﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Security;

namespace CloudStorageLight.Core.Web
{
    public class ClientToken
    {
        public string InitIPAddress { get; set; }
        public string UserName { get; set; }
        public DateTime IsuueDate { get; set; }
        public DateTime ExpireDate { get; set; }

        public string ToToken()
        {
            var ticket = new FormsAuthenticationTicket(1, UserName, IsuueDate, ExpireDate, false, InitIPAddress, "/");
            return FormsAuthentication.Encrypt(ticket);
        }

        public static ClientToken Parse(string ticketString)
        {
            try
            {
                var ticket = FormsAuthentication.Decrypt(ticketString);
                return new ClientToken()
                {
                    UserName = ticket.Name,
                    IsuueDate = ticket.IssueDate,
                    ExpireDate = ticket.Expiration,
                    InitIPAddress = ticket.UserData,
                };
            }
            catch (Exception)
            {

                return null;
            }
        }
    }
}
